<?php 
namespace app\admin\controller;
class Plugin extends Common {

	public function index(){
		$dir = PROJECT_PATH . 'plugin/';
		$plugins = [];
		if (is_dir($dir)) {
		    $dh = opendir($dir);
		    while ($file = readdir($dh)) {
		        if ($file != "." && $file != "..") {
		            $fullpath = $dir . "/" . $file;
		            if (is_dir($fullpath)) {
		            	if (file_exists($fullpath . '/config.php')) {
		            		$plugins[$file] = require $fullpath . '/config.php';
		            	}
		            }
		        }
		    }
		}
		$this -> assign('plugins', $plugins);

		$myplugs = \Plugin::plugins();
		$this -> assign('myplugs', $myplugs);
		
		return $this -> html($this -> fetch());
	}

	public function status(){
		if (\Ebcms::isAjax()) {
			$path = \mylib\Input::post('path');
			$dir = PROJECT_PATH . 'plugin/' . $path;
			if (!file_exists($dir . '/_config.php')) {
				return $this -> error('插件未安装！');
			}
			if (!file_exists($dir . '/config.php')) {
				return $this -> error('插件文件丢失！');
			}
			$_config = include $dir . '/_config.php';
			$_config['status'] = $_config['status'] ? 0 : 1;
			if (!file_put_contents($dir . '/_config.php', '<?php '.PHP_EOL.'return ' . var_export($_config, true) . ';')) {
				return $this -> error('操作失败！');
			}
			\mylib\Cache::delete('plugins');
			return $this -> success('操作成功！');
		}
	}

	public function install(){
		if (\Ebcms::isAjax()) {
			$path = \mylib\Input::post('path');
			$dir = PROJECT_PATH . 'plugin/' . $path;
			if (file_exists($dir . '/_config.php')) {
				return $this -> error('已经安装过了！');
			}
			if (!file_exists($dir . '/config.php')) {
				return $this -> error('插件文件丢失！');
			}

			$config = include $dir . '/config.php';
			if (true !== $msg = $config['install']()) {
				return $this -> error('安装失败！' . $msg);
			}
			$_config = [
				'status' => 0,
				'hooks'=>array_keys((isset($config['hooks'])&&$config['hooks']?$config['hooks']:[]))
			];
			if (!file_put_contents($dir . '/_config.php', '<?php '.PHP_EOL.'return ' . var_export($_config, true) . ';')) {
				return $this -> error('安装失败！');
			}
			\mylib\Cache::delete('plugins');
			return $this -> success('安装成功！');
		}
	}

	public function uninstall(){
		if (\Ebcms::isAjax()) {
			$path = \mylib\Input::post('path');
			$dir = PROJECT_PATH . 'plugin/' . $path;
			if (!file_exists($dir . '/_config.php')) {
				return $this -> error('插件未安装！');
			}
			if (!file_exists($dir . '/config.php')) {
				return $this -> error('插件文件丢失！');
			}

			$config = include $dir . '/config.php';
			if (true !== $msg = $config['uninstall']()) {
				return $this -> error('卸载失败！' . $msg);
			}

			@unlink($dir . '/_config.php');
			\mylib\Cache::delete('plugins');
			return $this -> success('卸载成功！');
		}
	}
}